package com.xy6.effectivejava.chapter02.item02;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * noninstantiable class for service registration and access
 * 
 * @author zhang
 *
 */
public class Services {

	private Services() {
	}

	// maps service names to services
	private static final Map<String, Provider> providers = new ConcurrentHashMap<>();

	public static final String DEFAULT_PROVIDER_NAME = "provider";

	// provider registration api
	public static void registerDefaultProvider(Provider p){
		registerProvider(DEFAULT_PROVIDER_NAME, p);
	}
	
	public static void registerProvider(String name, Provider p){
		providers.put(name, p);
	}
	
	public static Service newInstance(){
		return newInstance(DEFAULT_PROVIDER_NAME);
	}
	
	// service access api
	public static Service newInstance(String name){
		Provider p = providers.get(name);
		if(null == p){
			throw new IllegalArgumentException("no provider registered with name:" + name);
		}
		return p.newService();
	}
	
}
